using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LevelCamera : MonoBehaviour
{
    void FixedUpdate()
    {
        UpdateFollowPlayer();
    }
    // 摄像头跟随玩家移动
    private void UpdateFollowPlayer()
    {
        // 玩家的位置
        IEnumerable<Vector3> playersPosition = Player.GetAlivePlayersInScene()
            .Transform((Player player) =>
            {
                return player.transform.position;
            });

        //最靠左的位置
        Vector3 minPosition = playersPosition.Min((Vector3 p1, Vector3 p2) =>
        {
            float v = p1.x - p2.x;
            return Mathf.Approximately(v, 0.0f) ? 0 : (v < 0 ? -1 : 1);
        });
        //最靠右的位置
        Vector3 maxPosition = playersPosition.Max((Vector3 p1, Vector3 p2) =>
        {
            float v = p1.x - p2.x;
            return Mathf.Approximately(v, 0.0f) ? 0 : (v < 0 ? -1 : 1);
        });
        // 摄像头位置为所有玩家位置的中心
        Vector3 playersCenterPosition = minPosition + (maxPosition - minPosition) / 2f;

        Vector3 cameraPosition = transform.position;
        // 不允许向左移动
        if (playersCenterPosition.x > cameraPosition.x)
        {
            cameraPosition.x = playersCenterPosition.x;
        }
        transform.position = cameraPosition;
    }    
}
